# encoding: utf-8
class UsersController < ApplicationController

  # users_controller method for handling logins.
  #
  # POST data params[:username] and params[:password] are
  # passed to the User model method that handles the authentication.
  #
  # Upon successful authentication we store the credentials to
  # session[:user] hash and redirect to root_path.
  #
  def login
    if request.post?
      if session[:user] = User.authenticate(params[:username], params[:password])
        session[:user][:username] = params[:username]
        session[:user][:password] = params[:password]
        # flash[:notice] = 'Kirjautuminen onnistui'
        redirect_to root_path
      else
        flash[:notice] = 'Väärä käyttäjänimi/salasana tai palvelu on alhaalla'
      end
    elsif session[:user] != nil
      flash[:notice] = 'Kirjaudu ensin ulos'
      redirect_to root_path
    end
  end

  # users_controller method for handling logouts.
  #
  # session[:user] hash is cleared and user redirected
  # to the login page.
  #
  def logout
    session[:user] = nil
    flash[:notice] = 'Kirjauduit ulos'
    redirect_to :action => 'login'
  end
end
